package com.luyuan.crm.member.web.converter;

import java.util.List;

import javax.annotation.Resource;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

import org.springframework.stereotype.Component;

import com.luyuan.crm.member.model.Member;
import com.luyuan.crm.member.model.MemberCoupon;
import com.luyuan.crm.member.model.MemberCouponType;
import com.luyuan.crm.member.service.MemberCouponService;
import com.ruijie.foundation.dao.support.HibernateUtils;

@Component("memberCouponsConverter")
public class MemberCouponsConverter implements Converter {
    @Resource(name = "memberCouponService")
    private MemberCouponService memberCouponService;

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String value) {
        return null;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object value) {
        if (value == null) {
            return "";
        }
        if (!(HibernateUtils.resolveRealObject(value) instanceof Member)) {
            return "";
        }
        int a = 0;
        int b = 0;
        List<MemberCoupon> memberCoupons = memberCouponService.findByMember((Member) HibernateUtils
                .resolveRealObject(value));
        for (MemberCoupon memberCoupon : memberCoupons) {
            if (memberCoupon.getCouponType() == MemberCouponType.A) {
                a += memberCoupon.getAmount();
            }
            else if (memberCoupon.getCouponType() == MemberCouponType.B) {
                b += memberCoupon.getAmount();
            }
        }
        return "A券" + a + ";B券" + b + ";";
    }
}
